// dataQueryMixin.js
import {
    getSupplyChain,
    getIndustryCompanies,
    getCompanyRisks,
    getHighTechCompanies,
    getCompanyStats,
    getProductChain,
    getSupplyChainPath,
    searchProducts,
    getIndustryAnalysis,
    getIndustryComprehensiveAnalysis,
    getKeyMaterials
} from '@/api/graphAnalysis';
import { searchCompanies } from '@/api/company';
import { ref, reactive, computed } from 'vue';
import { ElMessage } from 'element-plus';

export const dataQueryMixin = {
    setup() {
        const supplyChainForm = reactive({
            companyName: '',
            depth: 2
        });
        const industryForm = reactive({
            industryName: ''
        });
        const riskForm = reactive({
            industryName: '',
            minRiskCount: 10
        });
        const highTechForm = reactive({
            industryName: ''
        });
        const supplyPathForm = reactive({
            sourceCompany: '',
            targetCompany: '',
            maxDepth: 3
        });
        const productChainForm = reactive({
            productName: '',
            selectedProduct: null,
            depth: 2,
            direction: 'both'
        });
        const industryComprehensiveForm = reactive({
            industryName: ''
        });
        const selectedIndustry = ref('');
        const analysisComplete = ref(false);
        const analysisData = ref(null);
        const comprehensiveData = ref(null);
        const keyMaterialsData = ref(null);
        const statsData = ref(null);
        const showGraph = ref(false);
        const loading = ref(false);
        const industryStats = ref(null);
        const permissionStatus = ref({
            base: true,
            supplyChain: true,
            industryChain: true,
            companyRisk: true,
            highTech: true,
            productChain: true,
            companyStats: true
        });

        const querySupplyChain = async () => {
            if (!permissionStatus.value.supplyChain) {
                ElMessage.error('您没有供应链分析权限，请联系管理员授权');
                return;
            }

            try {
                loading.value = true;
                const response = await getSupplyChain({
                    companyName: supplyChainForm.companyName.trim(),
                    depth: supplyChainForm.depth
                });

                graphData.value = {
                    nodes: response.nodes.map(n => ({
                        id: String(n.id),
                        name: n.name,
                        symbolSize: 50,
                        value: {
                            employeeCount: n.employeeCount,
                            companyScale: n.companyScale,
                            registeredCapital: n.registeredCapital,
                            establishYear: n.establishYear,
                            province: n.province,
                            riskCount: n.riskCount,
                            isHighTech: n.isHighTech
                        }
                    })),
                    relationships: response.links.map(r => ({
                        source: String(r.source),
                        target: String(r.target),
                        type: r.type || 'SUPPLIES',
                        value: r.type || '供应关系'
                    }))
                };

                nextTick(() => {
                    renderGraph();
                });
            } catch (error) {
                console.error('查询失败:', error);
                ElMessage.error('查询失败，请稍后重试');
            } finally {
                loading.value = false;
            }
        };

        const queryIndustry = async () => {
            if (!industryForm.industryName) {
                ElMessage.warning('请选择行业名称');
                return;
            }
            loading.value = true;
            try {
                const response = await getIndustryCompanies({
                    industryName: industryForm.industryName
                });

                if (response && response.companies && response.companies.length > 0) {
                    const industryName = industryForm.industryName;

                    const companyCount = response.companies.length;
                    const totalEmployees = response.companies.reduce((sum, company) =>
                        sum + (company.employeeCount || 0), 0);
                    const totalCapital = response.companies.reduce((sum, company) =>
                        sum + (company.registeredCapital || 0), 0);
                    const avgEmployees = companyCount > 0 ? totalEmployees / companyCount : 0;
                    const avgCapital = companyCount > 0 ? totalCapital / companyCount : 0;

                    const scaleTypes = new Set();
                    response.companies.forEach(company => {
                        if (company.companyScale) scaleTypes.add(company.companyScale);
                    });
                    const scaleCount = scaleTypes.size;

                    const totalRiskCount = response.companies.reduce((sum, company) =>
                        sum + (company.riskCount || 0), 0);

                    const highTechCount = response.companies.filter(company =>
                        company.isHighTech).length;

                    graphData.value = {
                        nodes: response.companies.map(company => ({
                            id: company.id || company.name,
                            name: company.name,
                            symbolSize: 50,
                            value: {
                                employeeCount: company.employeeCount,
                                companyScale: company.companyScale,
                                registeredCapital: company.registeredCapital,
                                establishYear: company.establishYear,
                                province: company.province,
                                riskCount: company.riskCount,
                                isHighTech: company.isHighTech
                            }
                        })),
                        relationships: []
                    };

                    industryStats.value = {
                        industry: industryName,
                        companyCount: companyCount,
                        totalEmployees: totalEmployees,
                        avgCapital: avgCapital,
                        avgEmployees: avgEmployees,
                        scaleCount: scaleCount,
                        totalRiskCount: totalRiskCount,
                        highTechCount: highTechCount
                    };

                    nextTick(() => {
                        renderGraph();
                    });
                } else if (response && response.industry) {
                    industryStats.value = {
                        industry: response.industry,
                        companyCount: response.companyCount || 0,
                        totalEmployees: response.totalEmployees || 0,
                        avgCapital: response.avgCapital || 0,
                        avgEmployees: response.avgEmployees || 0,
                        scaleCount: response.scaleCount || 0,
                        totalRiskCount: response.totalRiskCount || 0,
                        highTechCount: response.highTechCount || 0
                    };

                    graphData.value = {
                        nodes: [
                            {
                                id: 'industry',
                                name: response.industry,
                                symbolSize: 50,
                                value: {
                                    companyCount: response.companyCount || 0,
                                    totalEmployees: response.totalEmployees || 0,
                                    avgCapital: response.avgCapital || 0,
                                    avgEmployees: response.avgEmployees || 0,
                                    scaleCount: response.scaleCount || 0,
                                    totalRiskCount: response.totalRiskCount || 0,
                                    highTechCount: response.highTechCount || 0
                                }
                            }
                        ],
                        relationships: []
                    };

                    nextTick(() => {
                        renderGraph();
                    });
                } else {
                    industryStats.value = null;
                    graphData.value = {
                        nodes: [],
                        relationships: []
                    };
                    ElMessage.warning('未找到相关行业数据');
                }
            } catch (error) {
                console.error('获取行业数据失败:', error);
                ElMessage.error('获取行业数据失败，请稍后重试');
            } finally {
                loading.value = false;
            }
        };

        const queryCompanyRisks = async () => {
            if (!riskForm.industryName) {
                ElMessage.warning('请选择行业名称');
                return;
            }
            loading.value = true;
            try {
                const response = await getCompanyRisks({
                    industryName: riskForm.industryName,
                    minRiskCount: riskForm.minRiskCount
                });

                if (response && response.riskyCompanies && response.riskyCompanies.length > 0) {
                    graphData.value = {
                        nodes: response.riskyCompanies.map(company => ({
                            id: company.company,
                            name: company.company,
                            symbolSize: 50,
                            value: {
                                riskCount: company.riskCount,
                                riskTypes: company.riskTypes,
                                employeeCount: company.employeeCount,
                                companyScale: company.companyScale,
                                registeredCapital: company.registeredCapital,
                                establishYear: company.establishYear,
                                province: company.province,
                                isHighTech: company.isHighTech
                            }
                        })),
                        relationships: []
                    };

                    industryStats.value = {
                        industry: response.industry,
                        minRiskThreshold: response.minRiskCount,
                        riskyCompanyCount: response.riskyCompanies.length
                    };

                    nextTick(() => {
                        renderGraph();
                    });
                } else {
                    graphData.value = {
                        nodes: [],
                        relationships: []
                    };
                    ElMessage.warning('未找到相关风险企业数据');
                }
            } catch (error) {
                console.error('查询失败:', error);
                ElMessage.error('查询失败，请稍后重试');
                graphData.value = {
                    nodes: [],
                    relationships: []
                };
            } finally {
                loading.value = false;
            }
        };

        const queryHighTechCompanies = async () => {
            if (!highTechForm.industryName) {
                ElMessage.warning('请选择行业名称');
                return;
            }
            loading.value = true;
            try {
                const response = await getHighTechCompanies({
                    industryName: highTechForm.industryName
                });

                if (response.data && (response.data.nodes || response.data.relationships)) {
                    graphData.value = response.data;
                } else if (response.industry || response.highTechCount) {
                    const industryName = response.industry || highTechForm.industryName;
                    const highTechCount = response.highTechCount || 0;
                    const avgRegisteredCapital = response.avgRegisteredCapital || 0;
                    const totalEmployees = response.totalEmployees || 0;

                    graphData.value = {
                        nodes: [
                            {
                                id: 'hightech-industry',
                                name: `${industryName} 高新技术企业`,
                                value: highTechCount,
                                type: 'hightech-industry',
                                properties: {
                                    industry: industryName,
                                    highTechCount: highTechCount,
                                    avgRegisteredCapital: avgRegisteredCapital,
                                    totalEmployees: totalEmployees
                                }
                            }
                        ],
                        relationships: []
                    };

                    industryStats.value = {
                        industry: industryName,
                        highTechCount: highTechCount,
                        avgRegisteredCapital: avgRegisteredCapital,
                        totalEmployees: totalEmployees
                    };
                } else {
                    ElMessage.warning('未找到高新技术企业数据');
                    graphData.value = { nodes: [], relationships: [] };
                }

                nextTick(() => {
                    renderGraph();
                });
            } catch (error) {
                console.error('查询失败:', error);
                ElMessage.error('查询失败，请稍后重试');
                graphData.value = { nodes: [], relationships: [] };
            } finally {
                loading.value = false;
            }
        };

        const querySupplyPath = async () => {
            if (!supplyPathForm.sourceCompany || !supplyPathForm.targetCompany) {
                ElMessage.warning('请输入源公司和目标公司名称');
                return;
            }
            loading.value = true;
            try {
                const response = await getSupplyChainPath({
                    sourceCompany: supplyPathForm.sourceCompany,
                    targetCompany: supplyPathForm.targetCompany,
                    maxDepth: supplyPathForm.maxDepth
                });

                if (response && response.nodes && response.nodes.length > 0) {
                    const processedNodes = response.nodes.map(node => ({
                        id: String(node.id || node.name),
                        name: node.name,
                        symbolSize: 50,
                        value: {
                            employeeCount: node.properties?.employee_count,
                            companyScale: node.properties?.company_scale,
                            registeredCapital: node.properties?.registered_capital,
                            establishYear: node.properties?.establish_year,
                            province: node.properties?.province,
                            riskCount: node.properties?.risk_count,
                            isHighTech: node.properties?.is_high_tech
                        }
                    }));

                    const processedRelationships = response.relationships.map(rel => ({
                        source: String(rel.source),
                        target: String(rel.target),
                        type: rel.type || 'SUPPLIES',
                        name: rel.type || 'SUPPLIES',
                        value: rel.type || '供应关系'
                    }));

                    graphData.value = {
                        nodes: processedNodes,
                        relationships: processedRelationships
                    };

                    nextTick(() => {
                        renderGraph();
                    });
                } else {
                    ElMessage.warning('未找到相关供应链路径数据');
                    graphData.value = { nodes: [], relationships: [] };
                }
            } catch (error) {
                console.error('查询失败:', error);
                ElMessage.error('查询失败，请稍后重试');
                graphData.value = { nodes: [], relationships: [] };
            } finally {
                loading.value = false;
            }
        };

        const queryCompanyStats = async () => {
            if (!permissionStatus.value.companyStats) {
                ElMessage.error('您没有企业统计分析权限，请联系管理员授权');
                return;
            }

            loading.value = true;
            statsData.value = null;

            try {
                // 获取当前行业名称
                let params = {};
                
                // 从不同表单中尝试获取当前行业名称
                if (industryForm.industryName) {
                    params.industryName = industryForm.industryName;
                } else if (riskForm.industryName) {
                    params.industryName = riskForm.industryName;
                } else if (highTechForm.industryName) {
                    params.industryName = highTechForm.industryName;
                }
                
                if (params.industryName) {
                    console.log('区域企业统计使用行业名称:', params.industryName);
                }

                const response = await getCompanyStats(params);
                console.log('区域企业统计数据原始响应:', response);

                let processedData = [];
                
                // 判断响应数据结构并提取数据
                if (response && Array.isArray(response) && response.length > 0) {
                    processedData = response;
                } else if (response && response.data && Array.isArray(response.data) && response.data.length > 0) {
                    processedData = response.data;
                } else {
                    console.warn('未找到区域企业统计数据或数据格式不正确:', response);
                    ElMessage.warning('未找到区域企业统计数据');
                    statsData.value = [];
                    loading.value = false;
                    return;
                }
                
                // 数据预处理: 确保所有必需字段都有值，格式化数值
                statsData.value = processedData.map(item => {
                    // 科学计数法处理
                    let totalCapital = item.totalCapital;
                    if (typeof totalCapital === 'string' && totalCapital.includes('E')) {
                        totalCapital = parseFloat(totalCapital);
                    }
                    if (typeof totalCapital === 'number' && !isNaN(totalCapital)) {
                        totalCapital = parseFloat(totalCapital.toFixed(2));
                    }
                    
                    return {
                        province: item.province || '未知',
                        companyCount: typeof item.companyCount === 'number' ? item.companyCount : 0,
                        totalEmployees: typeof item.totalEmployees === 'number' ? item.totalEmployees : 0,
                        totalCapital: totalCapital || 0,
                        highTechCount: typeof item.highTechCount === 'number' ? item.highTechCount : 0
                    };
                });
                
                console.log('处理后的区域企业统计数据:', statsData.value);
                
                // 按企业数量降序排序
                statsData.value.sort((a, b) => b.companyCount - a.companyCount);
                
                // 限制数据条数，避免图表拥挤
                if (statsData.value.length > 15) {
                    console.log(`数据量过大(${statsData.value.length}条)，仅展示前15条`);
                    const topData = statsData.value.slice(0, 15);
                    const otherProvincesData = statsData.value.slice(15);
                    
                    // 合并其他省份数据
                    if (otherProvincesData.length > 0) {
                        const otherData = {
                            province: '其他地区',
                            companyCount: otherProvincesData.reduce((sum, item) => sum + item.companyCount, 0),
                            totalEmployees: otherProvincesData.reduce((sum, item) => sum + item.totalEmployees, 0),
                            totalCapital: otherProvincesData.reduce((sum, item) => sum + item.totalCapital, 0),
                            highTechCount: otherProvincesData.reduce((sum, item) => sum + item.highTechCount, 0)
                        };
                        statsData.value = [...topData, otherData];
                    } else {
                        statsData.value = topData;
                    }
                }
                
                // 筛选出有效数据
                if (statsData.value.length > 0) {
                    nextTick(() => {
                        renderStatsCharts();
                    });
                } else {
                    ElMessage.warning('区域企业统计数据为空');
                }
            } catch (error) {
                console.error('查询区域企业统计失败:', error);
                ElMessage.error('查询区域企业统计失败: ' + (error.message || '请稍后重试'));
                statsData.value = [];
            } finally {
                loading.value = false;
            }
        };

        const queryProductChain = async () => {
            try {
                loading.value = true;
                const params = {
                    productName: productChainForm.productName || '',
                    depth: productChainForm.depth,
                    direction: productChainForm.direction
                };

                const response = await getProductChain(params);

                if (response && response.data) {
                    graphData.value = response.data;
                } else if (response && response.nodes) {
                    graphData.value = response;
                } else if (response && typeof response === 'object') {
                    graphData.value = response;
                } else {
                    console.warn('查询结果结构不符合预期:', response);
                    graphData.value = { nodes: [], relationships: [] };
                    loading.value = false;
                    return;
                }

                if (!graphData.value.nodes) graphData.value.nodes = [];
                if (!graphData.value.relationships) graphData.value.relationships = [];

                if (graphData.value.nodes.length === 0) {
                    ElMessage.warning('未找到相关产品关系数据');
                    loading.value = false;
                    return;
                }

                nextTick(() => {
                    renderProductChainGraph();
                });
            } catch (error) {
                console.error('查询产品上下游关系失败:', error);
                ElMessage.error('查询失败: ' + (error.message || '未知错误'));
                graphData.value = { nodes: [], relationships: [] };
                loading.value = false;
            }
        };

        const identifyKeyMaterials = async () => {
            try {
                loading.value = true;
                const response = await getKeyMaterials();

                if (!response || (!response.nodes && !response.keyMaterialsByConnection)) {
                    ElMessage.warning("未找到关键材料数据");
                    loading.value = false;
                    return;
                }

                graphData.value = {
                    nodes: response.nodes || [],
                    relationships: response.relationships || []
                };

                keyMaterialsData.value = {
                    keyMaterialsByConnection: response.keyMaterialsByConnection || [],
                    keyMaterialsByIntermediary: response.keyMaterialsByIntermediary || []
                };

                if (graphData.value.nodes.length > 0 && keyMaterialsData.value.keyMaterialsByConnection.length > 0) {
                    const keyMaterialIds = new Set(keyMaterialsData.value.keyMaterialsByConnection.map(m => m.id));

                    graphData.value.nodes = graphData.value.nodes.map(node => {
                        if (keyMaterialIds.has(node.id)) {
                            return {
                                ...node,
                                isKeyMaterial: true,
                                itemStyle: {
                                    color: "#FF5722",
                                    borderColor: "#FFD700",
                                    borderWidth: 2
                                }
                            };
                        }
                        return node;
                    });
                }

                nextTick(() => {
                    renderKeyMaterialsGraph();
                });

            } catch (error) {
                console.error("识别关键材料失败:", error);
                ElMessage.error("识别关键材料失败: " + (error.message || "未知错误"));
            } finally {
                loading.value = false;
            }
        };

        const renderProductChainGraph = () => {
            try {
                if (!graphData.value || !graphData.value.nodes || graphData.value.nodes.length === 0) {
                    console.warn("产品关系图数据为空，无法渲染");
                    loading.value = false;
                    return;
                }

                if (!graphContainer.value) {
                    console.error("找不到图表容器");
                    loading.value = false;
                    return;
                }

                if (graphChart.value) {
                    graphChart.value.dispose();
                }

                graphChart.value = echarts.init(graphContainer.value);

                const nodes = graphData.value.nodes.map(node => {
                    let symbolSize = 25;
                    let category = 0;

                    if (node.type === "Product") {
                        category = 0;
                    } else if (node.type === "Material") {
                        category = 1;
                    } else {
                        category = 2;
                    }

                    return {
                        id: node.id,
                        name: node.name,
                        symbolSize: symbolSize,
                        category: category,
                        label: {
                            show: true,
                            position: "right",
                            fontSize: 12
                        },
                        value: node.properties || {},
                        description: node.description || '',
                        type: node.type
                    };
                });

                const links = graphData.value.relationships.map(link => {
                    return {
                        source: link.source,
                        target: link.target,
                        value: link.type === "UPSTREAM_OF" ? "上游" : link.type,
                        type: link.type
                    };
                });

                const option = {
                    title: {
                        text: '产品链技术决策支持分析图',
                        subtext: '数据来源: 知识图谱',
                        top: 'top',
                        left: 'center'
                    },
                    tooltip: {
                        trigger: 'item',
                        formatter: function(params) {
                            if (params.dataType === 'node') {
                                return `
                  <div style="font-weight:bold;margin-bottom:5px;">${params.data.name}</div>
                  <div>类型: ${params.data.type || '产品'}</div>
                  ${params.data.description ? `<div>描述: ${params.data.description}</div>` : ''}
                `;
                            } else {
                                const sourceNode = nodes.find(n => n.id === params.data.source);
                                const targetNode = nodes.find(n => n.id === params.data.target);
                                const sourceName = sourceNode ? sourceNode.name : params.data.source;
                                const targetName = targetNode ? targetNode.name : params.data.target;

                                if (params.data.type === "UPSTREAM_OF") {
                                    return `${sourceName} 是 ${targetName} 的上游`;
                                } else {
                                    return `${sourceName} → ${targetName}: ${params.data.value}`;
                                }
                            }
                        }
                    },
                    legend: {
                        data: ['产品', '原材料', '其他'],
                        orient: 'vertical',
                        left: 'left',
                        top: 'middle'
                    },
                    series: [{
                        type: 'graph',
                        layout: 'force',
                        data: nodes,
                        links: links,
                        categories: [
                            { name: '产品' },
                            { name: '原材料' },
                            { name: '其他' }
                        ],
                        roam: true,
                        label: {
                            show: true,
                            position: 'right',
                            formatter: '{b}'
                        },
                        force: {
                            repulsion: 150,
                            gravity: 0.1,
                            edgeLength: [80, 120],
                            layoutAnimation: true
                        },
                        lineStyle: {
                            color: 'source',
                            curveness: 0.3
                        },
                        edgeSymbol: ['none', 'arrow'],
                        edgeSymbolSize: [0, 10],
                        edgeLabel: {
                            show: true,
                            formatter: '{c}',
                            fontSize: 12
                        },
                        emphasis: {
                            focus: 'adjacency',
                            lineStyle: {
                                width: 4
                            }
                        }
                    }]
                };

                graphChart.value.setOption(option);

                const resizeHandler = () => {
                    if (graphChart.value) {
                        graphChart.value.resize();
                    }
                };
                window.addEventListener('resize', resizeHandler);

                loading.value = false;

                console.log('产品关系图渲染完成');
            } catch (error) {
                console.error('渲染产品关系图失败:', error);
                loading.value = false;
                ElMessage.error('图表渲染失败: ' + (error.message || '未知错误'));
            }
        };

        const renderKeyMaterialsGraph = () => {
            try {
                if (!graphData.value || !graphData.value.nodes || graphData.value.nodes.length === 0) {
                    console.warn("关键材料图数据为空，无法渲染");
                    loading.value = false;
                    return;
                }

                if (!graphContainer.value) {
                    console.error("找不到图表容器");
                    loading.value = false;
                    return;
                }

                if (graphChart.value) {
                    graphChart.value.dispose();
                }

                const nodes = graphData.value.nodes.map(node => {
                    let symbolSize = 25;
                    let category = 0;

                    if (node.type === "Product") {
                        category = 0;
                    } else if (node.type === "Material") {
                        category = 1;
                    } else {
                        category = 2;
                    }

                    if (node.isKeyMaterial) {
                        symbolSize = 40;
                        category = 3;
                    }

                    return {
                        ...node,
                        symbolSize: symbolSize,
                        category: category,
                        label: {
                            show: true,
                            position: "right",
                            fontSize: 12
                        }
                    };
                });

                const links = graphData.value.relationships.map(link => {
                    return {
                        source: link.source,
                        target: link.target,
                        value: link.type === "UPSTREAM_OF" ? "上游" : link.type,
                        type: link.type,
                        lineStyle: {
                            width: 2,
                            curveness: 0.2
                        }
                    };
                });

                const option = {
                    title: {
                        text: "关键材料识别分析图",
                        subtext: "突出显示的节点为关键材料",
                        top: "top",
                        left: "center"
                    },
                    tooltip: {
                        trigger: "item",
                        formatter: function(params) {
                            if (params.dataType === "node") {
                                const node = params.data;
                                let tooltipContent = `
                  <div style="font-weight:bold;margin-bottom:5px;">${node.name}</div>
                  <div>类型: ${node.type || "产品"}</div>
                `;

                                if (node.isKeyMaterial) {
                                    tooltipContent += `<div style="color:#FF5722;font-weight:bold;">关键材料</div>`;
                                }

                                if (node.description) {
                                    tooltipContent += `<div>描述: ${node.description}</div>`;
                                }

                                return tooltipContent;
                            } else {
                                const sourceNode = nodes.find(n => n.id === params.data.source);
                                const targetNode = nodes.find(n => n.id === params.data.target);
                                const sourceName = sourceNode ? sourceNode.name : params.data.source;
                                const targetName = targetNode ? targetNode.name : params.data.target;

                                if (params.data.type === "UPSTREAM_OF") {
                                    return `${sourceName} 是 ${targetName} 的上游`;
                                } else {
                                    return `${sourceName} → ${targetName}: ${params.data.value}`;
                                }
                            }
                        }
                    },
                    legend: {
                        data: ["产品", "原材料", "其他", "关键材料"],
                        orient: "vertical",
                        left: "left",
                        top: "middle",
                        textStyle: {
                            fontSize: 12
                        }
                    },
                    series: [{
                        type: "graph",
                        layout: "force",
                        data: nodes,
                        links: links,
                        categories: [
                            { name: "产品" },
                            { name: "原材料" },
                            { name: "其他" },
                            { name: "关键材料", itemStyle: { color: "#FF5722" } }
                        ],
                        roam: true,
                        label: {
                            show: true,
                            position: "right",
                            formatter: "{b}",
                            fontSize: 12
                        },
                        force: {
                            repulsion: 200,
                            gravity: 0.1,
                            edgeLength: 100,
                            friction: 0.6,
                            layoutAnimation: true
                        },
                        lineStyle: {
                            color: "source",
                            curveness: 0.3
                        },
                        edgeSymbol: ["none", "arrow"],
                        edgeSymbolSize: [0, 10],
                        edgeLabel: {
                            show: true,
                            formatter: "{c}",
                            fontSize: 12
                        },
                        emphasis: {
                            focus: "adjacency",
                            lineStyle: {
                                width: 4
                            }
                        }
                    }]
                };

                graphChart.value.setOption(option);

                const resizeHandler = () => {
                    if (graphChart.value) {
                        graphChart.value.resize();
                    }
                };
                window.addEventListener("resize", resizeHandler);

                loading.value = false;

                console.log("关键材料网络图渲染完成");
            } catch (error) {
                console.error("渲染关键材料网络图失败:", error);
                loading.value = false;
                ElMessage.error("图表渲染失败: " + (error.message || "未知错误"));
            }
        };

        const queryIndustryComprehensive = async () => {
            if (!industryComprehensiveForm.industryName) {
                ElMessage.warning('请输入行业名称');
                return;
            }

            loading.value = true;

            try {
                const response = await getIndustryComprehensiveAnalysis({
                    industryName: industryComprehensiveForm.industryName
                });

                comprehensiveData.value = response;

                await nextTick();

                setTimeout(() => {
                    renderComprehensiveCharts();
                }, 1000);

                ElMessage.success('行业企业综合分析查询成功');
            } catch (error) {
                console.error('查询行业企业综合分析失败:', error);
                ElMessage.error('查询行业企业综合分析失败');
                showGraph.value = false;
            } finally {
                loading.value = false;
            }
        };

        const renderComprehensiveCharts = () => {
            try {
                if (!comprehensiveData.value) {
                    console.warn('未找到综合分析数据，无法渲染图表');
                    return;
                }

                const companySizeDOM = document.getElementById('companySizeChart');
                if (companySizeDOM) {
                    renderCompanySizeChart();
                }

                const comparisonDOM = document.getElementById('comparisonChart');
                if (comparisonDOM) {
                    renderComparisonChart();
                }

                const patentDistributionDOM = document.getElementById('patentDistributionChart');
                if (patentDistributionDOM) {
                    renderPatentDistributionChart();
                }

                const innovationEfficiencyDOM = document.getElementById('innovationEfficiencyChart');
                if (innovationEfficiencyDOM) {
                    renderInnovationEfficiencyChart();
                }
            } catch (error) {
                console.error('渲染综合分析图表发生错误:', error);
            }
        };

        const renderCompanySizeChart = () => {
            try {
                const chartDom = document.getElementById('companySizeChart');
                if (!chartDom) {
                    console.error('企业规模分布图表DOM元素不存在');
                    return;
                }

                if (!comprehensiveData.value || !comprehensiveData.value.companySizeDistribution ||
                    !Array.isArray(comprehensiveData.value.companySizeDistribution) ||
                    comprehensiveData.value.companySizeDistribution.length === 0) {
                    chartDom.innerHTML = '<div style="display:flex;justify-content:center;align-items:center;height:100%;">暂无数据</div>';
                    return;
                }

                const data = comprehensiveData.value.companySizeDistribution.map(item => {
                    return {
                        name: item.size || '未知规模',
                        value: item.count || 0
                    };
                });

                const chart = echarts.init(chartDom);

                const option = {
                    tooltip: {
                        trigger: 'item',
                        formatter: '{a} <br/>{b}: {c} ({d}%)'
                    },
                    legend: {
                        orient: 'vertical',
                        left: 'left',
                        top: 'middle',
                        itemWidth: 10,
                        itemHeight: 10,
                        textStyle: {
                            fontSize: 12
                        },
                        data: data.map(item => item.name)
                    },
                    series: [
                        {
                            name: '企业规模分布',
                            type: 'pie',
                            radius: '70%',
                            center: ['60%', '50%'],
                            avoidLabelOverlap: false,
                            itemStyle: {
                                borderRadius: 6,
                                borderColor: '#fff',
                                borderWidth: 2
                            },
                            label: {
                                show: true,
                                formatter: '{b}: {c} ({d}%)',
                                fontSize: 12
                            },
                            emphasis: {
                                label: {
                                    show: true,
                                    fontSize: '14',
                                    fontWeight: 'bold'
                                }
                            },
                            data: data
                        }
                    ]
                };

                chart.setOption(option);

                window.addEventListener('resize', () => {
                    chart.resize();
                });
            } catch (error) {
                console.error('渲染企业规模分布图表错误:', error);
            }
        };

        const renderComparisonChart = () => {
            try {
                const chartDom = document.getElementById('comparisonChart');
                if (!chartDom) {
                    console.error('高新企业与普通企业比较图表DOM元素不存在');
                    return;
                }

                if (!comprehensiveData.value || !comprehensiveData.value.hightechComparison ||
                    !Array.isArray(comprehensiveData.value.hightechComparison) ||
                    comprehensiveData.value.hightechComparison.length === 0) {
                    chartDom.innerHTML = '<div style="display:flex;justify-content:center;align-items:center;height:100%;">暂无数据</div>';
                    return;
                }

                const hightechData = comprehensiveData.value.hightechComparison.find(item => item.isHighTech === true) || { avgEmployees: 0, avgCapital: 0, avgPatents: 0 };
                const regularData = comprehensiveData.value.hightechComparison.find(item => item.isHighTech === false) || { avgEmployees: 0, avgCapital: 0, avgPatents: 0 };

                const chart = echarts.init(chartDom);

                const option = {
                    tooltip: {
                        trigger: 'axis'
                    },
                    radar: {
                        indicator: [
                            { name: '员工人数', max: Math.max(hightechData.avgEmployees, regularData.avgEmployees) * 1.2 || 1000 },
                            { name: '注册资本', max: Math.max(hightechData.avgCapital, regularData.avgCapital) * 1.2 || 5000 },
                            { name: '专利数量', max: Math.max(hightechData.avgPatents, regularData.avgPatents) * 1.2 || 100 }
                        ]
                    },
                    series: [
                        {
                            type: 'radar',
                            data: [
                                {
                                    value: [
                                        Math.round(hightechData.avgEmployees),
                                        hightechData.avgCapital,
                                        hightechData.avgPatents
                                    ],
                                    name: '高新技术企业',
                                    areaStyle: {
                                        color: 'rgba(64, 158, 255, 0.4)'
                                    }
                                },
                                {
                                    value: [
                                        Math.round(regularData.avgEmployees),
                                        regularData.avgCapital,
                                        regularData.avgPatents
                                    ],
                                    name: '普通企业',
                                    areaStyle: {
                                        color: 'rgba(103, 194, 58, 0.4)'
                                    }
                                }
                            ]
                        }
                    ]
                };

                chart.setOption(option);

                window.addEventListener('resize', () => {
                    chart.resize();
                });
            } catch (error) {
                console.error('渲染高新企业与普通企业比较图表错误:', error);
            }
        };

        const renderPatentDistributionChart = () => {
            try {
                const chartDom = document.getElementById('patentDistributionChart');
                if (!chartDom) {
                    console.error('专利分布图表DOM元素不存在');
                    return;
                }

                if (!comprehensiveData.value || !comprehensiveData.value.patentDistribution ||
                    !Array.isArray(comprehensiveData.value.patentDistribution) ||
                    comprehensiveData.value.patentDistribution.length === 0) {
                    chartDom.innerHTML = '<div style="display:flex;justify-content:center;align-items:center;height:100%;">暂无数据</div>';
                    return;
                }

                const data = comprehensiveData.value.patentDistribution.slice(0, 10);

                const chart = echarts.init(chartDom);

                const option = {
                    tooltip: {
                        trigger: 'axis',
                        axisPointer: {
                            type: 'shadow'
                        }
                    },
                    grid: {
                        left: '3%',
                        right: '4%',
                        bottom: '15%',
                        top: '10%',
                        containLabel: true
                    },
                    xAxis: {
                        type: 'category',
                        data: data.map(item => item.company),
                        axisLabel: {
                            interval: 0,
                            rotate: 40,
                            fontSize: 10,
                            width: 70,
                            overflow: 'truncate'
                        }
                    },
                    yAxis: {
                        type: 'value',
                        name: '专利数量'
                    },
                    series: [{
                        name: '专利数量',
                        data: data.map(item => item.patents),
                        type: 'bar',
                        barWidth: '60%',
                        itemStyle: {
                            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                { offset: 0, color: '#83bff6' },
                                { offset: 0.5, color: '#188df0' },
                                { offset: 1, color: '#188df0' }
                            ])
                        },
                        emphasis: {
                            itemStyle: {
                                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                    { offset: 0, color: '#2378f7' },
                                    { offset: 0.7, color: '#2378f7' },
                                    { offset: 1, color: '#83bff6' }
                                ])
                            }
                        },
                        label: {
                            show: true,
                            position: 'top',
                            fontSize: 10
                        }
                    }]
                };

                chart.setOption(option);

                window.addEventListener('resize', () => {
                    chart.resize();
                });
            } catch (error) {
                console.error('渲染专利分布图表错误:', error);
            }
        };

        const renderInnovationEfficiencyChart = () => {
            try {
                const chartDom = document.getElementById('innovationEfficiencyChart');
                if (!chartDom) {
                    console.error('创新效率图表DOM元素不存在');
                    return;
                }

                if (!comprehensiveData.value || !comprehensiveData.value.innovationEfficiency ||
                    !Array.isArray(comprehensiveData.value.innovationEfficiency) ||
                    comprehensiveData.value.innovationEfficiency.length === 0) {
                    chartDom.innerHTML = '<div style="display:flex;justify-content:center;align-items:center;height:100%;">暂无数据</div>';
                    return;
                }

                const data = comprehensiveData.value.innovationEfficiency.slice(0, 10);

                const chart = echarts.init(chartDom);

                const option = {
                    tooltip: {
                        trigger: 'axis',
                        axisPointer: { type: 'shadow' },
                        formatter: function(params) {
                            const item = data[params[0].dataIndex];
                            return `${item.company}<br/>人均专利: ${item.efficiency.toFixed(2)}<br/>专利数: ${item.patents}<br/>员工数: ${item.employees}`;
                        }
                    },
                    grid: {
                        left: '3%',
                        right: '4%',
                        bottom: '15%',
                        top: '10%',
                        containLabel: true
                    },
                    xAxis: {
                        type: 'category',
                        data: data.map(item => item.company),
                        axisLabel: {
                            interval: 0,
                            rotate: 40,
                            fontSize: 10,
                            width: 70,
                            overflow: 'truncate'
                        }
                    },
                    yAxis: {
                        type: 'value',
                        name: '人均专利数'
                    },
                    series: [{
                        name: '创新效率',
                        type: 'bar',
                        barWidth: '60%',
                        data: data.map(item => item.efficiency),
                        itemStyle: {
                            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                { offset: 0, color: '#67C23A' },
                                { offset: 0.5, color: '#5DAF34' },
                                { offset: 1, color: '#4E9A2F' }
                            ])
                        },
                        emphasis: {
                            itemStyle: {
                                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                                    { offset: 0, color: '#5DAF34' },
                                    { offset: 0.7, color: '#4E9A2F' },
                                    { offset: 1, color: '#449028' }
                                ])
                            }
                        },
                        label: {
                            show: true,
                            position: 'top',
                            fontSize: 10,
                            formatter: function(params) {
                                return params.value.toFixed(2);
                            }
                        }
                    }]
                };

                chart.setOption(option);

                window.addEventListener('resize', () => {
                    chart.resize();
                });
            } catch (error) {
                console.error('渲染创新效率图表错误:', error);
            }
        };

        const getComparisonData = (isHighTech, field) => {
            if (!comprehensiveData.value || !comprehensiveData.value.hightechComparison) {
                return 0;
            }

            const data = comprehensiveData.value.hightechComparison.find(item => item.isHighTech === isHighTech);
            if (!data) {
                return 0;
            }

            if (field === 'avgEmployees') {
                return Math.round(data.avgEmployees);
            } else if (field === 'avgCapital') {
                return data.avgCapital;
            } else if (field === 'avgPatents') {
                return data.avgPatents.toFixed(1);
            }

            return 0;
        };

        return {
            supplyChainForm,
            industryForm,
            riskForm,
            highTechForm,
            supplyPathForm,
            productChainForm,
            selectedIndustry,
            analysisComplete,
            analysisData,
            comprehensiveData,
            keyMaterialsData,
            statsData,
            showGraph,
            loading,
            industryStats,
            querySupplyChain,
            queryIndustry,
            queryCompanyRisks,
            queryHighTechCompanies,
            querySupplyPath,
            queryCompanyStats,
            queryProductChain,
            identifyKeyMaterials,
            queryIndustryComprehensive,
            renderComprehensiveCharts,
            renderCompanySizeChart,
            renderComparisonChart,
            renderPatentDistributionChart,
            renderInnovationEfficiencyChart,
            getComparisonData
        };
    }
};